package com.sptpc.demo.service.impl;

import com.sptpc.demo.model.Drink;
import com.sptpc.demo.model.Order;
import com.sptpc.demo.repository.DrinkRepository;
import com.sptpc.demo.repository.OrderRepository;
import com.sptpc.demo.service.IOrderService;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderJpaService implements IOrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private DrinkRepository drinkRepository;


    @Override
    public void addNewOrder(Order newOrder, List<Integer> items) {
        newOrder.setState(0);//设置订单状态
        List<Drink> drinks= drinkRepository.findAllById(items);
        newOrder.setItems(drinks);
        BigDecimal priceum= drinks.stream()
                .map(drink -> drink.getPrice().getAmount())
                .reduce(BigDecimal.ZERO, ((total, price) -> total.add(price)));
        newOrder.setPrice(Money.of(CurrencyUnit.of("CNY"), priceum));
        orderRepository.save(newOrder);
    }

    @Override
    public  Order getOrderById(Integer id) {
        return orderRepository.findById(id).orElse(null);
    }

    @Override
    public void updataOrder(Order order) {
        orderRepository.save(order);
    }

    @Override
    public void deleteByid(Integer id) {
        orderRepository.deleteById(id);
    }

    @Override
    public List<Order> getOrderByCustomer(String customer) {
        Order order=new Order();
        order.setCustomer(customer);
        order.setState(1);
        Example<Order> example=Example.of(order);
        return  orderRepository.findAll(example);
    }
}